#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <syslog.h>
#include <time.h>
#include <string.h>

#include <stdbool.h>
#include <mysql.h>

#include "debug.h"
#include "wifidog_mgw.h"
#include "conf.h";

MYSQL* conn;

bool firstConnection=true;
char* confServer;
char* confUser;
char* confPassword;
char* confDatabase;
int confPort;

char *SuperStringsCat (char *String1, ...)
{
	va_list List;
	va_start (List, String1);
	unsigned int Size;
	Size = strlen (String1) + 1;
	char *s;
	s = String1;

	do
	{
		Size += strlen (s) + 1;
	}
	while ((s = va_arg (List, char*)) != NULL);

	char *Merge;
	Merge = (char*)malloc (sizeof (char) * Size);
	char *sMerge = Merge;

	va_end (List);
	va_start (List, String1);
	s = String1;

	do
	{
		strcpy (Merge, s);
		Merge += strlen (s);
	}
	while ((s = va_arg (List, char*)) != NULL);

	va_end (List);

	return sMerge;
}
void open_conn()
{
	//Connessione al database

	// Prende le info per la connessione al database dal file di configurazione

	debug(LOG_INFO, "WIFIDOG-MGW - Retrieving database informations from configuration file");
	s_config *configdb=config_get_config();
	char* server=configdb->server;
	char* user=configdb->user;
	char* password=configdb->password;
	char* database=configdb->database;
	int port=configdb->port;

	conn = mysql_init(NULL);
	debug(LOG_INFO, "WIFIDOG-MGW - DB inizialized");
	/* Connect to database */
	if (!mysql_real_connect(conn, server, user , password, database, port, NULL, 0))
	{
		fprintf(stderr, "%s\n", mysql_error(conn));
	}
	else
		debug(LOG_INFO, "WIFIDOG-MGW - DB connected");
}
void close_conn()
{
	mysql_close(conn);
	debug(LOG_INFO, "WIFIDOG-MGW - DB disconnected");
}
MYSQL_RES* query (char* input)
{
   // send SQL query
   /*
   res=query("select * from auth");

   // output table name
   printf("MySQL Tables in mysql database:\n");
   while ((row = mysql_fetch_row(res)) != NULL)
      printf("%s \n", row[0]);

   // close connection
   mysql_free_result(res);
   */
   if (mysql_query(conn, input)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      return 0;
   }

   return mysql_use_result(conn);
}
char* get_db_token (char* mac)
{
	MYSQL_RES *res;
	MYSQL_ROW row;
	// send SQL query
	char* temp="SELECT Token FROM auth WHERE MAC='";
	temp=SuperStringsCat(temp,mac,"'",NULL);
	res=query(temp);

   // output table name
   //printf("MySQL Tables in mysql database:\n");
   row = mysql_fetch_row(res);
   //mysql_free_result(res);
   return row[0];
}

void insert(char* username, char* date, char* ip, char* mac,char* token)
{
	char* temp="INSERT INTO auth VALUES ('";
	temp=SuperStringsCat(temp,username,"','",date,"','",ip,"','",mac,"','",token,"')",NULL);
	debug(LOG_INFO, "WIFIDOG-MGW - Execute query: %s\n",temp);
	mysql_query(conn,temp);
}
void update(char* mac, char* date)
{
	//UPDATE  `wifidog`.`auth` SET  `Date` =  '2011-09-28 14:34:34' WHERE  `auth`.`MAC` =  '00:00:00:00:00';
	char* temp="UPDATE auth SET Date ='";
	temp=SuperStringsCat(temp,date,"' WHERE MAC='",mac,"'",NULL);
	debug(LOG_INFO, "WIFIDOG-MGW - Execute query: %s\n",temp);
	mysql_query(conn,temp);
	printf("Query OK\n");
}
void delete(char* mac)
{
	char* temp="DELETE FROM auth WHERE MAC='";
	temp=SuperStringsCat(temp,mac,"'",NULL);
	mysql_query(conn,temp);
	debug(LOG_INFO, "WIFIDOG-MGW - Execute query: %s\n",temp);
}
bool check(char* mac)
{
	s_config *configdb=config_get_config();
	open_conn();
	MYSQL_RES *res;
	MYSQL_ROW row;
	time_t date;
	char* temp="SELECT Date FROM auth WHERE MAC='";
	temp=SuperStringsCat(temp,mac,"'",NULL);
	res=query(temp);
	if ((row = mysql_fetch_row(res)) != NULL)
	{
		struct tm boh;
		strptime(row[0],"%Y-%m-%d %I:%M:%S",&boh);
		date= mktime(&boh);
		double diff = difftime(time(NULL),date);
		mysql_free_result(res);
		debug(LOG_INFO, "WIFIDOG-MGW - Diff time: %f\n",diff);
		if(diff < (configdb->clienttimeout)*60)
		{
			close_conn();
			return true;
		}
		else
		{
			delete(mac);
		}
	}

	close_conn();
	return false;
}

//Funzione che restituisce data e ora corrente nel formato YYYY-MM-DD hh:mm
char* currentDatetime()
{
	time_t current = time(NULL);
	char date[15];
	char time[10];

	strftime(date, sizeof(date),"%Y-%m-%d", localtime(&current));
	strftime(time, sizeof(time), "%I:%M:%S", localtime(&current));

	char* dateAndTime=SuperStringsCat(date," ",time,NULL);
	return dateAndTime;
}

